package ua.com.minus1.lookbattle;

import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import ua.com.minus1.lookbattle.menu.ClicksActionView;
import ua.com.minus1.lookbattle.models.CommonResult;
import ua.com.minus1.lookbattle.net.HttpManager;
import ua.com.minus1.lookbattle.net.URLManager;
import ua.com.minus1.lookbattle.utils.AppPreferences;

import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: Igorek
 * Date: 10/31/12
 * Time: 10:16 PM
 * To change this template use File | Settings | File Templates.
 */
public class StartActivity extends SherlockFragmentActivity {
    private HttpManager mHttpManager;
    private AppPreferences mPreferences;
    private ClicksActionView mClicksActionView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        mHttpManager = new HttpManager(this);
        mPreferences = new AppPreferences(this);

        if (mPreferences.getUUID().length() == 0) {
            resetUuid();
            sendInitInfo();
        }
    }

    private void resetUuid() {
        String uuid = UUID.randomUUID().toString();
        mPreferences.setUUID(uuid);
        mPreferences.setRegistered(false);
    }

    private void sendInitInfo() {
        Point windowSize = getWindowSize();
        mHttpManager.loadClass(URLManager.getStartUrl(mPreferences.getUUID(), windowSize.x, windowSize.y), CommonResult.class, new HttpManager.HttpResultHandler<CommonResult>() {
            public void onResultLoadComplete(CommonResult result) {
                Log.i(MainActivity.class.getName(), "onStart result status " + result.status);
                mPreferences.setClicks(result.clicks);
            }
        });
    }

    private Point getWindowSize() {
        Point size = new Point();
        WindowManager w = getWindowManager();

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
            w.getDefaultDisplay().getSize(size);
        }else{
            Display d = w.getDefaultDisplay();
            size.x = d.getWidth();
            size.y = d.getHeight();
        }

        return size;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getSupportMenuInflater().inflate(R.menu.start, menu);
        mClicksActionView = (ClicksActionView) menu.findItem(R.id.menu_start_clicks).getActionView();
        mClicksActionView.setClicks(mPreferences.getClicks());
        return true;
    }
}
